package service

import (
	"bridge_viewing/db"
	"bridge_viewing/dto"
	"bridge_viewing/dto/user"
	"bridge_viewing/global"
	"bridge_viewing/model"
	"bridge_viewing/static"
	"bridge_viewing/utils"
)

// GetUserById @Description: 根据用户id获取用户
func GetUserById(baseParam *dto.BaseParam, userId int) *model.User {
	var userEntity model.User
	result := db.DBGClient.First(&userEntity, userId)
	if result.Error != nil {
		global.GetLogger().ErrorByTrace(baseParam, "not found the user_id:%d", userId)
		return nil
	}
	return &userEntity
}

// GetUserByPhone @Description: 通过手机号获取用户信息
func GetUserByPhone(baseParam *dto.BaseParam, userPhone string) *model.User {
	var entityUser model.User
	result := db.DBGClient.Where(&model.User{UserPhone: userPhone}).First(&entityUser)
	if result.Error != nil {
		global.GetLogger().InfoByTrace(baseParam, "not found the phone:%s", userPhone)
		return nil
	}
	return &entityUser
}

func GenerateDefaultNickname(userPhone string) string {
	nickname := static.UserNicknamePrefix
	if userPhone != "" {
		nickname += userPhone[7:]
	} else {
		nickname += utils.GenerateNumberCode(4)
	}
	return nickname
}

// AddUserInfo @Description: 新增用户，返回user_id
func AddUserInfo(baseParam *dto.BaseParam, userPhone string) (int, error) {
	entityUser := model.User{
		UserPhone: userPhone,
	}
	result := db.DBGClient.Create(&entityUser)
	if result.Error != nil {
		global.GetLogger().ErrorByTrace(baseParam, "add user is error:%s", result.Error.Error())
		return 0, result.Error
	}
	return entityUser.UserId, nil
}

// GetUserInfoById @Description: 获取用户基本信息，手机号加密返回
func GetUserInfoById(baseParam *dto.BaseParam, userId int) *user.UserInfo {
	userEntity := GetUserById(baseParam, userId)
	if userEntity == nil {
		return nil
	}
	userInfo := user.UserInfo{
		UserId:    userEntity.UserId,
		UserPhone: utils.FormatMobileStar(userEntity.UserPhone),
	}
	return &userInfo
}

func UpdateUserInfoById(baseParam *dto.BaseParam, userId int, info model.User) {
	db.DBGClient.Model(&model.User{UserId: userId}).Updates(info)
}
